<?php defined('SYSPATH') or die('No direct access allowed.');

/**
 * 会员折扣
 * Class Model_Api_V2_Discount
 */
class Model_Api_V2_Discount
{
    //添加订单会员折扣
    public static function add_order_discount($arr)
    {
        if (!St_Functions::is_normal_app_install('memberdiscount') || !$arr['memberid'] || !$arr['productautoid']) {
            //没安装或没有会员id,直接返回
            return '';
        }
        if ($arr['typeid'] == 21) {
            return '';
        }
        $rank           = Model_Member::member_rank($arr['memberid'], array('return' => 'all'));
        if(!$rank['member_discount']){
            return '';
        }
        /*判断是否是子订单，是的话判断主订单是否是组合产品，是的话就不参与会员价*/
        if ($arr['pid']) {
            $p_typeid = DB::select()->from("member_order")->where("id={$arr['pid']}")->execute()->get('typeid');
            if ($p_typeid == 23) {
                return '';
            }
        }
        $order          = Model_Member_Order::order_info($arr['ordersn']);
        $product_id     = $order['productautoid'];
        $member_id      = $order['memberid'];
        $type_id        = $order['typeid'];
        $commissiontype = Model_Discount_Config::get_val('cfg_discount_commission_type_' . $type_id);
        $discount_price = 0;
        if ($type_id != 1 && $type_id != 114) {
            $price    = $order['price'] * $order['dingnum'];
            $discount = self::get_discount_info($member_id, $type_id, $product_id);
            if ($commissiontype == 1) {
                if ($price > 0 && $discount > 0) {
                    $discount_price += $price * (100 - $discount) / 100;
                }
            } else if($commissiontype == 2){
                //产品价格存在
                if ($price > 0) {
                    $discount_price = bcmul($discount,$order['dingnum'],2);
                }
            } else {
                //产品价格存在
                if ($price > 0) {
                    $discount_price += $discount;
                }
            }
        }
        else
        {
            $rankid         = intval($rank['current_rank']['id']);
            $commissiontype = Model_Discount_Config::get_val('cfg_discount_commission_type_' . $type_id);
            if($commissiontype==1){
                $commission = 'ratio';
            }else if($commissiontype==2){
                $commission = 'cumulative';
            }else{
                $commission = 'cash';
            }
            if ($type_id == 1)
            {
                $people_group = Model_Sysconfig::get_people_group();
                foreach ($people_group as $k => &$_val) {
                    $discount_arr = DB::select()->from('discount_config')->where('groupid', '=', 0)
                        ->and_where('varname', '=', 'dis_' . $rankid . '_' . $commission . '_' . $type_id . '_' . $_val['identifier'] . '_' . $product_id)
                        ->execute()->current();
                    if (!$discount_arr || !$discount_arr['value'])//没有具体设置,获得全局配置
                    {
                        $discount_arr = DB::select()->from('discount_config')->where('groupid', '=', 0)
                            ->and_where('varname', '=', 'cfg_discount_' . $rankid . '_' . $commission . '_' . $_val['identifier'] . '_' . $type_id)
                            ->execute()->current();
                    }
                    $discount = $discount_arr['value'] ? doubleval($discount_arr['value']) : 0;

                    if ($commissiontype == 1) {
                        switch ($k) {
                            case 2:
                                if ($order['price'] * $order['dingnum'] > 0 && $discount > 0) {
                                    $discount_price += $order['price'] * $order['dingnum'] * (100 - $discount) / 100;
                                }
                                break;
                            case 1:
                                if ($order['childprice'] * $order['childnum'] > 0 && $discount > 0) {
                                    $discount_price += $order['childprice'] * $order['childnum'] * (100 - $discount) / 100;
                                }
                                break;
                            case 3:
                                if ($order['oldprice'] * $order['oldnum'] > 0 && $discount > 0) {
                                    $discount_price += $order['oldprice'] * $order['oldnum'] * (100 - $discount) / 100;
                                }
                                break;
                            case 4:
                                if ($order['people4_price'] * $order['people4_num'] > 0 && $discount > 0) {
                                    $discount_price += $order['people4_price'] * $order['people4_num'] * (100 - $discount) / 100;
                                }
                                break;
                            case 5:
                                if ($order['people5_price'] * $order['people5_num'] > 0 && $discount > 0) {
                                    $discount_price += $order['people5_price'] * $order['people5_num'] * (100 - $discount) / 100;
                                }
                                break;
                            case 6:
                                if ($order['people6_price'] * $order['people6_num'] > 0 && $discount > 0) {
                                    $discount_price += $order['people6_price'] * $order['people6_num'] * (100 - $discount) / 100;
                                }
                                break;
                        }

                    } else if($commissiontype == 2){
                        switch ($k) {
                            case 2:
                                if ($order['price'] * $order['dingnum'] > 0 && $discount > 0) {
                                    $discount_price = bcmul($discount,$order['dingnum'],2);
                                }
                                break;
                            case 1:
                                if ($order['childprice'] * $order['childnum'] > 0 && $discount > 0) {
                                    $discount_price = bcmul($discount,$order['childnum'],2);
                                }
                                break;
                            case 3:
                                if ($order['oldprice'] * $order['oldnum'] > 0 && $discount > 0) {
                                    $discount_price = bcmul($discount,$order['oldnum'],2);
                                }
                                break;
                            case 4:
                                if ($order['people4_price'] * $order['people4_num'] > 0 && $discount > 0) {
                                    $discount_price = bcmul($discount,$order['people4_num'],2);
                                }
                                break;
                            case 5:
                                if ($order['people5_price'] * $order['people5_num'] > 0 && $discount > 0) {
                                    $discount_price = bcmul($discount,$order['people5_num'],2);
                                }
                                break;
                            case 6:
                                if ($order['people6_price'] * $order['people6_num'] > 0 && $discount > 0) {
                                    $discount_price = bcmul($discount,$order['people6_num'],2);
                                }
                                break;
                        }
                    } else {
                        switch ($k) {
                            case 2:
                                if ($order['price'] * $order['dingnum'] > 0 && $discount > 0) {
                                    $discount_price += $discount;
                                }
                                break;
                            case 1:
                                if ($order['childprice'] * $order['childnum'] > 0 && $discount > 0) {
                                    $discount_price += $discount;
                                }
                                break;
                            case 3:
                                if ($order['oldprice'] * $order['oldnum'] > 0 && $discount > 0) {
                                    $discount_price += $discount;
                                }
                                break;
                            case 4:
                                if ($order['people4_price'] * $order['people4_num'] > 0 && $discount > 0) {
                                    $discount_price += $discount;
                                }
                                break;
                            case 5:
                                if ($order['people5_price'] * $order['people5_num'] > 0 && $discount > 0) {
                                    $discount_price += $discount;
                                }
                                break;
                            case 6:
                                if ($order['people6_price'] * $order['people6_num'] > 0 && $discount > 0) {
                                    $discount_price += $discount;
                                }
                                break;
                        }
                    }
                }
            }
            elseif ($type_id == 114)
            {
                $people_group = array(
                    '2' => array(
                        'identifier' => 2,
                        'index' => 'price',
                    ),
                    '1' => array(
                        'identifier' => 1,
                        'index' => 'childprice',
                    ),
                );
                foreach ($people_group as $k => &$_val) {
                    $discount_arr = DB::select()->from('discount_config')->where('groupid', '=', 0)
                        ->and_where('varname', '=', 'dis_' . $rankid . '_' . $commission . '_' . $type_id . '_' . $_val['identifier'] . '_' . $product_id)
                        ->execute()->current();
                    if (!$discount_arr || !$discount_arr['value'])//没有具体设置,获得全局配置
                    {
                        $discount_arr = DB::select()->from('discount_config')->where('groupid', '=', 0)
                            ->and_where('varname', '=', 'cfg_discount_' . $rankid . '_' . $commission . '_' . $_val['identifier'] . '_' . $type_id)
                            ->execute()->current();
                    }
                    $discount = $discount_arr['value'] ? doubleval($discount_arr['value']) : 0;


                    if ($commissiontype == 1) {
                        switch ($k) {
                            case 2:
                                if ($order['price'] * $order['dingnum'] > 0 && $discount > 0) {
                                    $discount_price += $order['price'] * $order['dingnum'] * (100 - $discount) / 100;
                                }
                                break;
                            case 1:
                                if ($order['childprice'] * $order['childnum'] > 0 && $discount > 0) {
                                    $discount_price += $order['childprice'] * $order['childnum'] * (100 - $discount) / 100;
                                }
                                break;
                        }
                    }else if($commissiontype == 2){
                        switch ($k) {
                            case 2:
                                if ($order['price'] * $order['dingnum'] > 0 && $discount > 0) {
                                    $discount_price = bcmul($discount,$order['dingnum'],2);
                                }
                                break;
                            case 1:
                                if ($order['childprice'] * $order['childnum'] > 0 && $discount > 0) {
                                    $discount_price = bcmul($discount,$order['childnum'],2);
                                }
                                break;
                        }
                    } else {
                        switch ($k) {
                            case 2:
                                if ($order['price'] * $order['dingnum'] > 0 && $discount > 0) {
                                    $discount_price += $discount;
                                }
                                break;
                            case 1:
                                if ($order['childprice'] * $order['childnum'] > 0 && $discount > 0) {
                                    $discount_price += $discount;
                                }
                                break;
                        }
                    }
                }
            }
        }
        if($discount_price > 0)
        {
            $discount_price = min($discount_price, doubleval($order['payprice']));
            $record = DB::select()
                ->from('member_order_discount')
                ->where('order_id', '=', $order['id'])
                ->execute()
                ->current();
            if (empty($record)) {
                //TODO
                $data = array(
                    'order_id' => $order['id'],
                    'amount' => $discount_price,
                    'member_id' => $order['memberid'],
                    'type' => $commissiontype,
                );
                DB::insert('member_order_discount', array_keys($data))->values(array_values($data))->execute();
            } else {
                $data = array(
                    'amount' => $discount_price,
                    'member_id' => $order['memberid'],
                    'type' => $commissiontype,
                );
                DB::update('member_order_discount')->set($data)->where("order_id", "=", $order['id'])->execute();
            }
        }
    }

    public static function get_discount_new($member_id = '', $type_id, $product_id, $price, $cfg_minprice_rule = 2)
    {
        if ($type_id == 21) {
            return '';
        }

        if (!St_Functions::is_normal_app_install('memberdiscount')) {
            return '';
        }

        if (!$member_id && $type_id == 2)//单酒店新增改动
        {
            //没有登录,返回最低等级会员折扣
            $sql    = "select a.id,a.name,a.begin,a.end from sline_member_grade as a where 1=1 order by a.begin asc limit 0,20";
            $list   = DB::query(Database::SELECT, $sql)->execute()->as_array();
            $rankid = intval($list[0]['id']);

            $commissiontype = Model_Discount_Config::get_val('cfg_discount_commission_type_' . $type_id);
            $commission     = $commissiontype == 0 ? 'cash' : 'ratio';
            $discount_arr   = DB::select()->from('discount_config')->where('groupid', '=', 0)
                ->and_where('varname', '=', 'dis_' . $rankid . '_' . $commission . '_' . $type_id . '_0_' . $product_id)
                ->execute()->current();
            if (!$discount_arr || !$discount_arr['value'])//没有具体设置,获得全局配置
            {
                $discount_arr = DB::select()->from('discount_config')->where('groupid', '=', 0)
                    ->and_where('varname', '=', 'cfg_discount_' . $rankid . '_' . $commission . '_' . $type_id)
                    ->execute()->current();
            }
            $discount = $discount_arr['value'] ? doubleval($discount_arr['value']) : '';
            if ($commissiontype == 1)//百分比折扣
            {
                if ($discount) {
                    $price_arr = $price * ($discount / 100);
                } else {
                    $price_arr = '';
                }
            } else //固定金额折扣
            {
                if ($discount && $discount <= $price) {
                    $price_arr = $price - $discount;
                } else {
                    $price_arr = '';
                }
            }

            $price_arr = floatval(number_format($price_arr, 2, '.', ''));
            return $price_arr;
        }

        if ($type_id != 1 && $type_id != 114) {
            $commissiontype = Model_Discount_Config::get_val('cfg_discount_commission_type_' . $type_id);
            $discount       = self::get_discount_info($member_id, $type_id, $product_id);
            $price_arr      = self::get_discount_price($discount, $commissiontype, $price);
        } else//线路,户外处理
        {
            $commissiontype = Model_Discount_Config::get_val('cfg_discount_commission_type_' . $type_id);
            $discount       = self::get_discount_info($member_id, $type_id, $product_id, $cfg_minprice_rule);
            $price_arr      = self::get_discount_price($discount, $commissiontype, $price);
        }

        return $price_arr;
    }

    /**
     * 获取会员折扣后的价格
     * @param $member_id
     * @param $type_id
     * @param $product_id
     * @param $price
     * @param $cfg_minprice_rule
     * @return float|string
     */
    public static function get_discount($member_id = '', $type_id, $product_id, $price, $cfg_minprice_rule = 2)
    {
        if ($type_id == 21 || !$member_id) {
            return '';
        }

        if (!St_Functions::is_normal_app_install('memberdiscount')) {
            //没安装或没有会员id,直接返回
            return '';
        }

        if ($type_id != 1 && $type_id != 114) {
            $cfg_minprice_rule = 0;
        }

        $commission_type = Model_Discount_Config::get_val('cfg_discount_commission_type_' . $type_id);
        $discount        = self::get_discount_info($member_id, $type_id, $product_id, $cfg_minprice_rule);
        return self::get_discount_price($discount, $commission_type, $price);
    }

    /**
     * 获取折扣设定值
     * @param $mid
     * @param $type_id
     * @param $product_id
     * @param $cfg_minprice_rule
     * @return float|int
     */
    public static function get_discount_info($mid, $type_id, $product_id, $cfg_minprice_rule = 0)
    {
        if ($type_id == 21) {
            return 0;
        }

        // 如果是线路或者户外，没有配置最低价规则时使用成人价
        if ($type_id == 1 || $type_id == 114) {
            $cfg_minprice_rule = $cfg_minprice_rule ?: 2;
        }

        $cfg_minprice_rule = $cfg_minprice_rule ?: 0;

        $rank    = Model_Member::member_rank($mid, array('return' => 'all'));
        if(!$rank['member_discount']){
            //验证当前等级是否支持会员折扣  不支持直接为0
            return 0;
        }
        $rank_id = intval($rank['current_rank']['id']);

        $commissiontype = Model_Discount_Config::get_val('cfg_discount_commission_type_' . $type_id);
        if($commissiontype==1){
            $commission = 'ratio';
        }else if($commissiontype==2){
            $commission = 'cumulative';
        }else{
            $commission = 'cash';
        }

        $key          = "dis_{$rank_id}_{$commission}_{$type_id}_{$cfg_minprice_rule}_{$product_id}";
        $discount_val = Model_Discount_Config::get_val($key, 0);
        if (!$discount_val) {
            $normal_key   = $cfg_minprice_rule ? "cfg_discount_{$rank_id}_{$commission}_{$cfg_minprice_rule}_{$type_id}" : "cfg_discount_{$rank_id}_{$commission}_{$type_id}";
            $discount_val = Model_Discount_Config::get_val($normal_key, 0);
        }

        $discount = $discount_val ?: 0;

        return floatval(number_format($discount, 2, '.', ''));
    }

    /**
     * 计算折扣后的价格
     * @param $discount
     * @param $commission_type
     * @param $price
     * @return float
     */
    public static function get_discount_price($discount, $commission_type, $price)
    {
        if ($commission_type == 1) {
            //百分比折扣
            if ($discount) {
                $price_arr = $price * ($discount / 100);
            } else {
                $price_arr = '';
            }
        } else if($commission_type == 2){
            //累计固定金额折扣
            if ($discount && $discount <= $price) {
                $price_arr = $price - $discount;
            } else {
                $price_arr = '';
            }
        } else {
            //固定金额折扣
            if ($discount && $discount <= $price) {
                $price_arr = $price - $discount;
            } else {
                $price_arr = '';
            }
        }

        return floatval(number_format($price_arr, 2, '.', ''));
    }

    /**
     * 获取通用产品折扣价
     * @param $rank_id
     * @param $type_id
     * @param $product_id
     * @return array
     */
    public static function normal_discount($rank_id, $type_id, $product_id)
    {
        $commission_key  = "cfg_discount_commission_type_{$type_id}";
        $commission_type = Model_Discount_Config::get_val($commission_key, 0);
        if($commission_type==1){
            $commission = 'ratio';
        }else if($commission_type==2){
            $commission = 'cumulative';
        }else{
            $commission = 'cash';
        }

        $key          = "dis_{$rank_id}_{$commission}_{$type_id}_0_{$product_id}";
        $discount_val = Model_Discount_Config::get_val($key, 0);
        if ($discount_val === '' || $discount_val === null) {
            $normal_key   = "cfg_discount_{$rank_id}_{$commission}_{$type_id}";
            $discount_val = Model_Discount_Config::get_val($normal_key, 0);
        }

        $discount = $discount_val ? floatval($discount_val) : 0;

        $data['discount']['price'] = $discount;
        $data['commissiontype']    = $commission_type;

        return $data;
    }

    /**
     * 获取线路折扣金额
     * @param $rank_id
     * @param $type_id
     * @param $product_id
     * @return array
     */
    public static function line_discount($rank_id, $type_id, $product_id)
    {
        $commission_key  = "cfg_discount_commission_type_{$type_id}";
        $commission_type = Model_Discount_Config::get_val($commission_key, 0);
        if($commission_type==1){
            $commission = 'ratio';
        }elseif($commission_type==2){
            $commission = 'cumulative';
        }else{
            $commission = 'cash';
        }

        $people_group  = Model_Sysconfig::get_people_group();
        $discount_data = array();
        $people_arr    = array(
            '1' => 'childprice',
            '2' => 'price',
            '3' => 'oldprice',
            '4' => 'people4',
            '5' => 'people5',
            '6' => 'people6'
        );
        foreach ($people_group as $k => &$_val) {
            $key = "dis_{$rank_id}_{$commission}_{$type_id}_{$_val['identifier']}_{$product_id}";

            $discount_val = Model_Discount_Config::get_val($key, 0);

            //没有具体设置,获得全局配置
            if ($discount_val === null) {
                $normal_key   = "cfg_discount_{$rank_id}_{$commission}_{$_val['identifier']}_{$type_id}";
                $discount_val = Model_Discount_Config::get_val($normal_key, 0);
            }

            $index                 = $people_arr[$k] ?? 'price';
            $discount              = $discount_val ? floatval($discount_val) : 0;
            $discount_data[$index] = $discount;
        }
        $data['discount']       = $discount_data;
        $data['commissiontype'] = $commission_type;

        return $data;
    }


    /**
     * 户外产品折扣金额
     * @param $rank_id
     * @param $type_id
     * @param $product_id
     * @return array
     */
    public static function outdoor_discount($rank_id, $type_id, $product_id)
    {
        $commission_key  = "cfg_discount_commission_type_{$type_id}";
        $commission_type = Model_Discount_Config::get_val($commission_key, 0);
        if($commission_type==1){
            $commission = 'ratio';
        }else if($commission_type==2){
            $commission = 'cumulative';
        }else{
            $commission = 'cash';
        }

        $people_group  = array(
            '2' => array(
                'identifier' => 2,
                'index' => 'price',
            ),
            '1' => array(
                'identifier' => 1,
                'index' => 'childprice',
            ),
        );
        $discount_data = array();
        foreach ($people_group as &$_val) {

            $key          = "dis_{$rank_id}_{$commission}_{$type_id}_{$_val['identifier']}_{$product_id}";
            $discount_val = Model_Discount_Config::get_val($key, 0);

            //没有具体设置,获得全局配置
            if ($discount_val === null) {
                $normal_key   = "cfg_discount_{$rank_id}_{$commission}_{$_val['identifier']}_{$type_id}";
                $discount_val = Model_Discount_Config::get_val($normal_key, 0);
            }

            $discount                      = $discount_val ? floatval($discount_val) : 0;
            $discount_data[$_val['index']] = $discount;
        }
        $data['discount']       = $discount_data;
        $data['commissiontype'] = $commission_type;

        return $data;
    }

    //获取产品的的套餐id和最低利润
    public static function get_profit_suitid($typeid,$v)
    {
        return Model_Product_Profit::get_product_profit($typeid, $v);
    }
}